package cn.sjx;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.sjx.modules.nbiot.handler.ReceiveServerAioHandler;
import org.springframework.beans.factory.annotation.Value;
import org.tio.core.udp.UdpServer;
import org.tio.core.udp.UdpServerConf;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.SocketException;

/**
 * TIO服务类
 *
 * @Author: sjx
 * @Date: 2019年08月30日 0030 17:06:14
 */
public class TioUdpServer {

    private static final Log logger = LogFactory.get();

    /**
     * UdpServer对象
     */
    private UdpServer udpServer;

    /**
     * 监听的端口
     */
    @Value("${geomagnetic.server.port}")
    private int serverPort;

    /**
     * 超时时间
     */
    @Value("${geomagnetic.server.timeout}")
    private int timeout;

    /**
     * 初始化Bean的时候执行的初始化方法
     */
    @PostConstruct
    public void init() {
        try {
            ReceiveServerAioHandler receiveServerAioHandler = new ReceiveServerAioHandler();
            UdpServerConf udpServerConf = new UdpServerConf(serverPort, receiveServerAioHandler, timeout);
            this.udpServer = new UdpServer(udpServerConf);

            // 启动Tio-udp服务
            this.udpServer.start();
            logger.info("");
            logger.info("=================================");
            logger.info("======> 【地磁|监听|启动】UDP服务启动成功：端口 = {}", serverPort);
            logger.info("=================================");
            logger.info("");
        } catch (SocketException e) {
            logger.info("======> 【地磁|监听|启动】UDP服务启动失败：{}", e.getMessage());
        }
    }

    /**
     * 销毁前停止udp服务
     */
    @PreDestroy
    public void destroy() {
        udpServer.stop();
    }
}